package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.business.builder.StepBuilder;
import com.ray.business.check.StepCheck;
import com.ray.business.service.ProdStepService;
import com.ray.business.table.dto.StepQueryDTO;
import com.ray.business.table.entity.ProdStep;
import com.ray.business.table.params.step.StepCreateParams;
import com.ray.business.table.params.step.StepEditParams;
import com.ray.business.table.params.step.StepQueryParams;
import com.ray.business.table.vo.StepVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 步骤相关服务
 * @Class: StepApi
 * @Package com.ray.base.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class StepApi {

    @Autowired
    private ProdStepService prodStepService;


    /**
     * 查询步骤列表信息 分页  非删除的
     * @param queryParams
     * @return
     */
    public Result<IPage<StepVO>> pageSteps(CommonPage<StepQueryParams,Page<StepVO>> queryParams){
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<StepQueryDTO,ProdStep> commonPageBuilder = new CommonPageBuilder<>(StepQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdStep> page = prodStepService.page(commonPageBuilder.bulid(),loginUser);
        List<ProdStep> steps = page.getRecords();
        //结果对象
        IPage<StepVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if(ObjectUtil.isNotNull(steps)){
            pageList.setRecords(steps.stream().map(sysStep -> {
                StepVO stepVO = new StepVO();
                BeanUtil.copyProperties(sysStep,stepVO);
                return  stepVO;
            }).collect(Collectors.toList()));
        }else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,pageList);
    }

    /**
     * 查询步骤列表信息--启用的步骤
     * @param queryParams
     * @return
     */
    public Result<List<StepVO>> querySteps(StepQueryParams queryParams){
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        StepQueryDTO queryDTO = new StepQueryDTO();
        BeanUtil.copyProperties(queryParams,queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<ProdStep> steps = prodStepService.list(queryDTO,loginUser);
        //查询对象
        List<StepVO> list = new ArrayList<>();
        if(ObjectUtil.isNotNull(steps)){
            list = steps.stream().map(sysStep -> {
                StepVO stepVO = new StepVO();
                BeanUtil.copyProperties(sysStep,stepVO);
                return  stepVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,list);
    }




    /**
     * 创建步骤
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createStep(StepCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdStep prodStep = prodStepService.queryStepByStepName(createParams.getStepName(), loginUser);
        new StepCheck(prodStep).checkStepName(null,SysMsgCodeConstant.Error.ERR10000002);
        StepBuilder stepBuilder = new StepBuilder();
        stepBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存步骤信息
        if(!prodStepService.save(stepBuilder.bulid())){
            log.info("保存步骤接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
       return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 编辑步骤
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editStep(StepEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdStep prodStep = prodStepService.queryStepByStepName(editParams.getStepName(), loginUser);
        new StepCheck(prodStep).checkStepName(editParams.getStepCode(),SysMsgCodeConstant.Error.ERR10000002);
        StepBuilder stepBuilder = new StepBuilder();
        stepBuilder.append(editParams).appendEdit(loginUser);
        //编辑步骤信息
        if(!prodStepService.edit(stepBuilder.bulid(),loginUser)){
            log.info("编辑步骤接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }


    /**
     * 删除步骤
     * @param stepCode 步骤编码
     * @return Result
     */
    @Transactional
    public Result<String> deleteStep(String stepCode) {
        ValidateUtil.hasLength(stepCode,"参数[stepCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdStep sysStep = prodStepService.queryStepByStepCode(stepCode,loginUser);
        new StepCheck(sysStep).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        StepBuilder stepBuilder = new StepBuilder();
        stepBuilder.appendCode(stepCode).appendEdit(loginUser).delete();
        //删除步骤信息
        if(!prodStepService.edit(stepBuilder.bulid(),loginUser)){
            log.info("删除步骤接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 开启步骤
     * @param stepCode 步骤编码
     * @return Result
     */
    @Transactional
    public Result<String> openStep(String stepCode) {
        ValidateUtil.hasLength(stepCode,"参数[stepCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdStep sysStep = prodStepService.queryStepByStepCode(stepCode,loginUser);
        new StepCheck(sysStep).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        StepBuilder stepBuilder = new StepBuilder();
        stepBuilder.appendCode(stepCode).appendEdit(loginUser).open();
        //开启步骤信息
        if(!prodStepService.edit(stepBuilder.bulid(),loginUser)){
            log.info("开启步骤接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 开启步骤
     * @param stepCode 步骤编码
     * @return Result
     */
    @Transactional
    public Result<String> closeStep(String stepCode) {
        ValidateUtil.hasLength(stepCode,"参数[stepCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdStep sysStep = prodStepService.queryStepByStepCode(stepCode,loginUser);
        new StepCheck(sysStep).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        StepBuilder stepBuilder = new StepBuilder();
        stepBuilder.appendCode(stepCode).appendEdit(loginUser).close();
        //关闭步骤信息
        if(!prodStepService.edit(stepBuilder.bulid(),loginUser)){
            log.info("关闭步骤接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 步骤详情
     * @param stepCode 步骤编码
     * @return Result
     */
    public Result<StepVO> viewStep(String stepCode) {
        ValidateUtil.hasLength(stepCode,"参数[stepCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdStep sysStep = prodStepService.queryStepByStepCode(stepCode,loginUser);
        new StepCheck(sysStep).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        StepVO stepVO = new StepVO();
        BeanUtil.copyProperties(sysStep,stepVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,stepVO);
    }

}
